<?php
namespace app\admin\controller;
use think\Controller;
use think\Session;
use app\common\controller\Login;
use think\Request;
use think\Db;
class Type extends Login
{
	public function index()
	{


		$data = db('shop_type')->order('sort ')->paginate(5);

		$page = $data->render();
		$this->assign('page',$page);

		$this->assign('data',$data);
		//var_dump($data);die;
		return $this->fetch();
	}

	public function update($id)
	{

		$data = db('shop_type')->find($id);
		$this->assign('data',$data);

		return $this->fetch();
	}

	public function do_update()
	{
		$data = input('post.');

		if (empty($data['shop_type_name'])) {
			return $this->error('请填写需要更改的名称！');
		}
		//var_dump($data);die;
		$type = db('shop_type')->find($data['id']);

		$data['pic'] = $this->img();

		if ($data['pic'] == 1) {

				$data['pic'] = $type['pic'];
			}


		  db('shop_type')->update($data);


			return $this->redirect('admin/type/index');

	}

	public function delete($id)
	{
		$static = db('shop_type')->delete($id);

		if ($static) {
			return $this->redirect('admin/type/index');
		}else{
			return $this->error('发生未知错误，请重试！');
		}
	}


	public function add()
	{
		return $this->fetch();
	}

	public function do_add()
	{
		$data = input('post.');
		if (empty($data['shop_type_name'])) {
			return $this->error('填写名称呀！');
		}
		$data['post_time'] = date('Y-m-d H:i:s');
		$data['agent_id'] = session::get('agent_id');
		$data['pic'] = $this->img();
		if ($data['pic'] == 1) {
			# code...
			$this->error('请选择图片');
		}
		//var_dump($data);die;
		  db('shop_type')->insert($data);


			return $this->redirect('admin/type/index');

	}

	public function img()
	{

		  $file = request()->file('img');
		   if (!$file) {

		   		return 1;
		   }




		    $info = $file->validate(['ext'=>'png,jpg,gif,jpeg'])->move(ROOT_PATH . 'public/uploads/shop');
		    if($info){
		    	//echo 1;die;
		    	  $nowDate=date('Ymd');
		      return  $nowDate.'/'.$info->getFilename();
		    }else{

		       return $this->error('错误!请重新上传图片.');
		    }
	}

	public function type_static($id)
	{
		$type = db('shop_type')->find($id);

		if ($type['static'] == 1) {
			$data['static'] = 2;

		}else if($type['static'] ==2){
			$data['static'] = 1;
		}

		$data['id'] = $type['id'];

		db('shop_type')->update($data);

		return $this->redirect('admin/type/index');
	}

}
